package com.huawei.filter;
import com.huawei.config.FilterProperties;
import com.huawei.config.JwtProperties;
import com.huawei.utils.JsonUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import java.util.Map;
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private FilterProperties filterProperties;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        //返回false不拦截
        //获取request
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String uri = request.getRequestURI();
        logger.debug("当前接口uri:",uri);
        System.out.println("当前接口uri:"+uri);
        List<String> allowPaths = filterProperties.getAllowPaths();
        //判断是否拦截
        boolean isFilter = true;
        //如果请求的uri在允许的列表之内，循环停止，并且不拦截
        for (String allowPath : allowPaths) {
            if (uri.startsWith(allowPath)) {
                isFilter = false;
                break;
            }
        }
        return isFilter;
    }

    @Override
    public Object run() throws ZuulException {
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        RequestContext currentContext = RequestContext.getCurrentContext();
        Cookie[] cookies=RequestContext.getCurrentContext().getRequest().getCookies();
        if(cookies==null){
            logger.info("进入网关,cookies为",cookies);
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(200);
            currentContext.setResponseBody("403");
        }
        String url=request.getRequestURL().toString();
        String cookie=null;
        if(cookies!=null&&!cookies.equals(null)){
            for (Cookie cookieEach : cookies) {
                if(url.indexOf("/api/item/admin")>-1&&"shop_admin_tick_tocken".equals(cookieEach.getName())){
                    cookie=cookieEach.getValue();
                }
                if(url.indexOf("/api/item/customer")>-1&&"shop_tick_tocken".equals(cookieEach.getName())){
                    cookie=cookieEach.getValue();
                }
            }
        }

        try {
            //不为空再去解析token
            if (StringUtils.isNotBlank(cookie)) {
                String token=cookie;
                ClassPathResource classPathResource = new ClassPathResource("huaweishop.jks");
                KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "huaweishop".toCharArray());
                KeyPair keyPair = keyStoreKeyFactory.getKeyPair("huaweishop");
                RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
                Jws<Claims> claimsJws= Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
                Map<String,Object> body=claimsJws.getBody();
                currentContext.setSendZuulResponse(true);
                if(body==null){
                    currentContext.setSendZuulResponse(false);
                    currentContext.setResponseStatusCode(200);
                    logger.info("进入网关,body为",body);
                    currentContext.setResponseBody("403");
                }
            } else {
                currentContext.setSendZuulResponse(false);
                currentContext.setResponseStatusCode(200);
                currentContext.setResponseBody("403");
            }

        } catch (Exception e) {
            e.printStackTrace();
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(200);
            currentContext.setResponseBody("403");
        }
        return null;
    }
}

